package whu.o2o.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.w3c.dom.Element;

import android.app.Activity;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import whu.o2o.R;

public class XmlUtil {

	
	public static String getXMLFileHead() {
		return "<?xml version=\"1.0\" encoding=\"GBK\"?>\n<root>\n";
	}

	public static String getXMLFileFoot() {
		return "\n</root>";
	}
    public static String getYcXml(String msg)
    {
    	StringBuffer sb=new StringBuffer();
    	sb.append(getXMLFileHead());
    	sb.append("<head>\n<code>1</code>\n<rows>0</rows>\n<message>"+msg+"</message>\n</head>");
    	sb.append(getXMLFileFoot());
    	return sb.toString();
    }

	/**
	 * 灏嗕腑鏂囧瓧绗︿覆杞崲涓簎tf-8鏍煎紡
	 */
	public static String encodeUTF8(String xmlDoc) {
		String str = "";
		try {
			str = URLEncoder.encode(xmlDoc, "utf-8");
		} catch (Exception ex) {
			str = ex.getMessage();
		}
		return str;
	}

	/**
	 * 灏唘tf-8鏍煎紡瀛楃涓茶浆鎹负涓枃瀛楃
	 */
	public static String decodeUTF8(String str) {
		String xmlDoc = "";
		try {
			xmlDoc = URLDecoder.decode(str, "utf-8");
		} catch (Exception ex) {
			xmlDoc = ex.getMessage();
		}
		return xmlDoc;
	}
	/**
	 * 从xml中获取message对象
	 * @param xml
	 * @return
	 */
	public static Message readFromXml(String xml)
	{
		Message msg=new Message();
		org.dom4j.Document doc = null;
		String code = "0";
		String message = "失败";
		String submitTime = "1";
	    String content= "0";
	    String userId="";
	    String orderNo="";
	    String infoid = "";
	    String status ="";
		try {
			doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
			org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
			Iterator headIter = rootElt.elementIterator("head"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
			// 锟斤拷锟斤拷head锟节碉拷
			if(headIter.hasNext()) {
				org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
				code = recordEle.elementTextTrim("code"); // 
				message = recordEle.elementTextTrim("message"); //
				content = recordEle.elementTextTrim("content");
			   userId=recordEle.elementTextTrim("userId");
			   orderNo=recordEle.elementTextTrim("orderNo");
			   submitTime =recordEle.elementTextTrim("submitTime");
			   infoid = recordEle.elementTextTrim("infoId");
			   status = recordEle.elementTextTrim("status");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			code="0";
			message="xml读取出现异常，请重试!";
		}
		

		return msg;
	}
	/**
	 * 从xml中获取文书编号
	 * @param xml
	 * @return
	 */
	public static Message readFromXmlWsbh(String xml)
	{
		Message msg=new Message();
		org.dom4j.Document doc = null;
		String code = "0";
		String message = "失败";
	    String wsbh="";
	 
		try {
			doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
			org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
			Iterator headIter = rootElt.elementIterator("head"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
			// 锟斤拷锟斤拷head锟节碉拷
			if(headIter.hasNext()) {
				org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
				code = recordEle.elementTextTrim("code"); // 
				message = recordEle.elementTextTrim("message"); //
			   wsbh=recordEle.elementTextTrim("wsbh");
			  
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			code="0";
			message="xml读取出现异常，请重试!";
		}
		
	
		//msg.setWsbh(wsbh);
	
		return msg;
	}
	/**
	 * xml锟斤拷莞锟绞阶拷锟斤拷锟斤拷锟捷革拷式
	 * 
	 * @param <T>
	 * @param xml
	 * @param entityClass
	 * @param message
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> readStringXmlOut(String xml, Class<T> entityClass,String element_Name) {
		List<T> l = new ArrayList<T>();
		org.dom4j.Document doc = null;
		int rownum = 0;
		String code = "";
		String message = "";
		String className = entityClass.getSimpleName();

		try {
			doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
			org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�

			Iterator headIter = rootElt.elementIterator("head"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
			// 锟斤拷锟斤拷head锟节碉拷
			while (headIter.hasNext()) {
				org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
				code = recordEle.elementTextTrim("code"); // 
				message = recordEle.elementTextTrim("message"); // 
			//	rownum = Integer.parseInt(recordEle.elementTextTrim("rownum"));
			}
			if (code.equals("1") && rownum >= 1) {
				Iterator bodyIter = rootElt.elementIterator("body"); // 
				Iterator classIter = null;
				org.dom4j.Element recordEless = null;
				org.dom4j.Element itemEle = null;
				Object nodeInstance = null;
				String fieldType = "";
				Object[] method = null;
				//
				while (bodyIter.hasNext()) {
					recordEless = (org.dom4j.Element) bodyIter.next();
					//
					classIter = recordEless.elementIterator(element_Name);

					/**
					 * 
					 */
					while (classIter.hasNext()) {
						// 锟斤拷锟斤拷className锟节碉拷锟铰的节碉拷
						itemEle = (org.dom4j.Element) classIter.next();
						nodeInstance = getInstanceClass(entityClass);
						if (nodeInstance == null) {
							System.err.println("该java实体类不存在！");
							break;
						}
						//
						for (Field field : entityClass.getDeclaredFields()) {
							/**
							 * 
							 */
							fieldType = field.getType().getName();
							if ("java.lang.String".equals(fieldType)) {
								try {
									method = beanMatch(entityClass, field.getName());
									if (method != null) {
										((Method) method[1]).invoke(nodeInstance, itemEle.elementTextTrim(field.getName().toLowerCase()));
									}
								} catch (Exception e) {
								}
							}
						}
						l.add((T) nodeInstance);
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}
	//登录返回xml解析
	public static <T> List<T> readLoginStringXmlOut(String xml, Class<T> entityClass,String element_Name) {
		List<T> l = new ArrayList<T>();
		org.dom4j.Document doc = null;
		int rownum = 0;
		String code = "";
		String message = "";
		String className = entityClass.getSimpleName();

		try {
			doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
			org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�

		
		
				Iterator bodyIter = rootElt.elementIterator("body"); // /锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絙ody
				Iterator classIter = null;
				org.dom4j.Element recordEless = null;
				org.dom4j.Element itemEle = null;
				Object nodeInstance = null;
				String fieldType = "";
				Object[] method = null;
				//
				while (bodyIter.hasNext()) {
					recordEless = (org.dom4j.Element) bodyIter.next();
					//
					classIter = recordEless.elementIterator(element_Name);

					/**
					 * 
					 */
					while (classIter.hasNext()) {
						// 锟斤拷锟斤拷className锟节碉拷锟铰的节碉拷
						itemEle = (org.dom4j.Element) classIter.next();
						nodeInstance = getInstanceClass(entityClass);
						if (nodeInstance == null) {
							System.err.println("该java实体类不存在！");
							break;
						}
						//
						for (Field field : entityClass.getDeclaredFields()) {
							/**
							 * 
							 */
							fieldType = field.getType().getName();
							if ("java.lang.String".equals(fieldType)) {
								try {
									method = beanMatch(entityClass, field.getName());
									if (method != null) {
										((Method) method[1]).invoke(nodeInstance, itemEle.elementTextTrim(field.getName()));
									}
								} catch (Exception e) {
								}
							}
						}
						l.add((T) nodeInstance);
					}
				}
			
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}
	//本地xml解析
	public static <T> List<T> readLocalStringXmlOut(String xml, Class<T> entityClass,String element_Name) {
		List<T> l = new ArrayList<T>();
		org.dom4j.Document doc = null;
		int rownum = 0;
		String code = "";
		String message = "";
		String className = entityClass.getSimpleName();

		try {
			doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
			org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�

		
		
				Iterator bodyIter = rootElt.elementIterator(""); // /锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絙ody
				Iterator classIter = null;
				org.dom4j.Element recordEless = null;
				org.dom4j.Element itemEle = null;
				Object nodeInstance = null;
				String fieldType = "";
				Object[] method = null;
				//
			
					//recordEless = (org.dom4j.Element) bodyIter.next();
					//
					classIter = rootElt.elementIterator(element_Name);

					/**
					 * 
					 */
					while (classIter.hasNext()) {
						// 锟斤拷锟斤拷className锟节碉拷锟铰的节碉拷
						itemEle = (org.dom4j.Element) classIter.next();
						nodeInstance = getInstanceClass(entityClass);
						if (nodeInstance == null) {
							System.err.println("该java实体类不存在！");
							break;
						}
						//
						for (Field field : entityClass.getDeclaredFields()) {
							/**
							 * 
							 */
							fieldType = field.getType().getName();
							if ("java.lang.String".equals(fieldType)) {
								try {
									method = beanMatch(entityClass, field.getName());
									if (method != null) {
										((Method) method[1]).invoke(nodeInstance, itemEle.elementTextTrim(field.getName()));
									}
								} catch (Exception e) {
								}
							}
						}
						l.add((T) nodeInstance);
					}
				
			
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}


	/**
	 * 
	 * 
	 * @param clazz
	 * @param beanProperty
	 *         
	 * @return object[0] : getter object[1] : setter
	 */
	public static <T> Object[] beanMatch(Class<T> clazz, String beanProperty) {
		Object[] result = new Object[2];
		char beanPropertyChars[] = beanProperty.toCharArray();
		beanPropertyChars[0] = Character.toUpperCase(beanPropertyChars[0]);
		String s = new String(beanPropertyChars);
		String names[] = { ("set" + s).intern(), ("get" + s).intern(),
				("is" + s).intern(), ("write" + s).intern(),
				("read" + s).intern() };
		Method getter = null;
		Method setter = null;
		Method methods[] = clazz.getMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			if (!Modifier.isPublic(method.getModifiers()))
				continue;
			String methodName = method.getName().intern();
			for (int j = 0; j < names.length; j++) {
				String name = names[j];
				if (!name.equals(methodName))
					continue;
				if (methodName.startsWith("set")
						|| methodName.startsWith("read"))
					setter = method;
				else
					getter = method;
			}
		}
		result[0] = getter;
		result[1] = setter;
		return result;
	}

	/**
	 * 
	 * 
	 * @param <T>
	 * @param entityClass
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public
	static <T> Object getInstanceClass(Class<T> entityClass) {
		try {
			Constructor con = entityClass.getConstructor(null);
			return con.newInstance(null);
		} catch (Exception e) {
			return null;
		}
	}
	 // 把一个字符串的第一个字母大写、效率是最高的、
	 public static String getMethodName(String fildeName) throws Exception{
	  byte[] items = fildeName.getBytes();
	  items[0] = (byte) ((char) items[0] - 'a' + 'A');
	  return new String(items);
	 }
	 public static Object getObjectValue(Object object) throws Exception {
		  //我们项目的所有实体类都继承BaseDomain （所有实体基类：该类只是串行化一下）
		  //不需要的自己去掉即可
		Object obj=null;
		  if (object != null) {//if (object!=null )  ----begin
		   // 拿到该类
		   Class<?> clz = object.getClass();
		   // 获取实体类的所有属性，返回Field数组
		   Field[] fields = clz.getDeclaredFields();
		   for (Field field : fields) {// --for() begin
		    System.out.println(field.getGenericType());//打印该类的所有属性类型
		    // 如果类型是String
		    if (field.getGenericType().toString().equals(
		      "class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
		     // 拿到该属性的gettet方法
		     
		     Method m = (Method) object.getClass().getMethod(
		       "get" + getMethodName(field.getName()));
		     String val = (String) m.invoke(object);// 调用getter方法获取属性值
		     if (val != null) {
		    	 obj=val;
		      System.out.println("String type:" + val);
		     }
		    }
		    // 如果类型是Integer
		    if (field.getGenericType().toString().equals(
		      "class java.lang.Integer")) {
		     Method m = (Method) object.getClass().getMethod(
		       "get" + getMethodName(field.getName()));
		     Integer val = (Integer) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("Integer type:" + val);
		     }
		    }
		    // 如果类型是Double
		    if (field.getGenericType().toString().equals(
		      "class java.lang.Double")) {
		     Method m = (Method) object.getClass().getMethod(
		       "get" + getMethodName(field.getName()));
		     Double val = (Double) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("Double type:" + val);
		     }
		    }
		    // 如果类型是Boolean 是封装类
		    if (field.getGenericType().toString().equals(
		      "class java.lang.Boolean")) {
		     Method m = (Method) object.getClass().getMethod(
		       field.getName());
		     Boolean val = (Boolean) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("Boolean type:" + val);
		     }
		    }
		    // 如果类型是boolean 基本数据类型不一样 这里有点说名如果定义名是 isXXX的 那就全都是isXXX的
		    // 反射找不到getter的具体名
		    if (field.getGenericType().toString().equals("boolean")) {
		     Method m = (Method) object.getClass().getMethod(
		       field.getName());
		     Boolean val = (Boolean) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("boolean type:" + val);
		     }
		    }
		    // 如果类型是Date
		    if (field.getGenericType().toString().equals(
		      "class java.util.Date")) {
		     Method m = (Method) object.getClass().getMethod(
		       "get" + getMethodName(field.getName()));
		     Date val = (Date) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("Date type:" + val);
		     }
		    }
		    // 如果类型是Short
		    if (field.getGenericType().toString().equals(
		      "class java.lang.Short")) {
		     Method m = (Method) object.getClass().getMethod(
		       "get" + getMethodName(field.getName()));
		     Short val = (Short) m.invoke(object);
		     if (val != null) {
		    	 obj=val;
		      System.out.println("Short type:" + val);
		     }
		    }
		    // 如果还需要其他的类型请自己做扩展
		   }//for() --end
		   
		  }//if (object!=null )  ----end
		  return obj;
		 }
	 /**
	  *获取某个静态类的静态属性值
	  * @param fileName
	  * @param entityClass
	  * @return
	  */
	 public static Object getFiledVal(String fileName,Class entityClass)
	 {
		 Object obj=null;
		 try {
			Field field = entityClass.getDeclaredField(fileName);
			obj =field.get(null);//
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return obj;
	 }
	 @SuppressWarnings("rawtypes")
		public static void  beanCopyTTT(Activity context,Object bean0,String prefix)
		{
			
		}
	    @SuppressWarnings("rawtypes")
		public static void  beanCopyT(Activity context,Object bean0,String prefix)
		{
			
		}
	  //登录返回xml解析
		public static <T> List<T> readchanageStringXmlOut(String xml, Class<T> entityClass,String element_Name,String element_Names) {
			List<T> l = new ArrayList<T>();
			org.dom4j.Document doc = null;
			int rownum = 0;
			String code = "";
			String message = "";
			String className = entityClass.getSimpleName();

			try {
				doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
				org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�

			
			
					Iterator bodyIter = rootElt.elementIterator("body"); // /锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絙ody
					Iterator classIter = null;
					Iterator classesIter = null;
					org.dom4j.Element recordEless = null;
					org.dom4j.Element itemEle = null;
					Object nodeInstance = null;
					String fieldType = "";
					Object[] method = null;
					//
					while (bodyIter.hasNext()) {
						recordEless = (org.dom4j.Element) bodyIter.next();
						//
						classesIter = recordEless.elementIterator(element_Names);
						
						while (classesIter.hasNext()) {
							 Element recordEles = (Element) classesIter.next();
							
						//	 classIter = recordEles.elementIterator(element_Name);
						while (classIter.hasNext()) {
							// 锟斤拷锟斤拷className锟节碉拷锟铰的节碉拷
							itemEle = (org.dom4j.Element) classIter.next();
							nodeInstance = getInstanceClass(entityClass);
							if (nodeInstance == null) {
								System.err.println("该java实体类不存在！");
								break;
							}
							//
							for (Field field : entityClass.getDeclaredFields()) {
								/**
								 * 
								 */
								fieldType = field.getType().getName();
								if ("java.lang.String".equals(fieldType)) {
									try {
										method = beanMatch(entityClass, field.getName());
										if (method != null) {
											((Method) method[1]).invoke(nodeInstance, itemEle.elementTextTrim(field.getName()));
										}
									} catch (Exception e) {
									}
								}
							}
							l.add((T) nodeInstance);
						}
					}
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return l;
		}
		
		public static String readContentXml(String xml,String element)
		{
			Message msg=new Message();
			org.dom4j.Document doc = null;
			String content = "0";
		
		   
			try {
				doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
				org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
				Iterator headIter = rootElt.elementIterator("body"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
				// 锟斤拷锟斤拷head锟节碉拷
				if(headIter.hasNext()) {
					org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
					content = recordEle.elementTextTrim(element); // 
					
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			
			}
			
		
			return content;
		}
		public static String readPicXml(String xml,String element)
		{
			Message msg=new Message();
			org.dom4j.Document doc = null;
			String pic = "";
		
		   
			try {
				doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
				org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
				Iterator headIter = rootElt.elementIterator("body"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
				// 锟斤拷锟斤拷head锟节碉拷
				if(headIter.hasNext()) {
					org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
					
					Iterator	classIter = recordEle.elementIterator("pics");
					if(classIter.hasNext()){
						org.dom4j.Element picEle = (org.dom4j.Element) classIter.next();
						pic = picEle.elementTextTrim("pic");
					}
					
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			
			}
			
		
			return pic;
		}
		
		public static String readuserIdXml(String xml,String element)
		{
			Message msg=new Message();
			org.dom4j.Document doc = null;
			String pic = "";
		
		   
			try {
				doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
				org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
				Iterator headIter = rootElt.elementIterator("body"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
				// 锟斤拷锟斤拷head锟节碉拷
				if(headIter.hasNext()) {
					org.dom4j.Element recordEle = (org.dom4j.Element) headIter.next();
					
					Iterator	classIter = recordEle.elementIterator("user");
					if(classIter.hasNext()){
						org.dom4j.Element picEle = (org.dom4j.Element) classIter.next();
						pic = picEle.elementTextTrim(element);
					}
					
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			
			}
			
		
			return pic;
		}
		public static ArrayList<String> readContentlistXml(String xml,String element)
		{
			Message msg=new Message();
			org.dom4j.Document doc = null;
			ArrayList<String>  content = new ArrayList<String>();
		
		   
			try {
				Iterator classIter = null;
				Iterator classesIter = null;
				org.dom4j.Element recordEless = null;
				org.dom4j.Element itemEle = null;
				doc = DocumentHelper.parseText(xml); // 锟斤拷锟街凤拷转为XML
				org.dom4j.Element rootElt = doc.getRootElement(); // 锟斤拷取锟斤拷诘锟�
				Iterator bodyIter = rootElt.elementIterator("body"); // 锟斤拷取锟斤拷诘锟斤拷碌锟斤拷咏诘锟絟ead
				// 锟斤拷锟斤拷head锟节碉拷
				while (bodyIter.hasNext()) {
					recordEless = (org.dom4j.Element) bodyIter.next();
					//
					classesIter = recordEless.elementIterator("titles");
					
					while (classesIter.hasNext()) {
						 Element recordEles = (Element) classesIter.next();
						
						 classIter = ((org.dom4j.Element) recordEles).elementIterator(element);
					while (classIter.hasNext()) {
						// 锟斤拷锟斤拷className锟节碉拷锟铰的节碉拷
						itemEle = (org.dom4j.Element) classIter.next();
					   String title = itemEle.getTextTrim();
					    Log.d("*********", title+"1");
						//
				
					   content.add(title);
					}
				}
			}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			
			}
			
		    Log.d("*********", content.size()+"");
			return content;
		}	
}
